package com.hst.web.base.service;

import java.util.Base64;
import java.util.Base64.Encoder;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.hst.core.dao.IORDao;
import com.hst.web.base.entity.TAccountIdentity;
import com.hst.web.base.entity.TAccountInfo;
import com.hst.web.base.entity.TCompanyEmployee;
import com.hst.web.base.ui.Register;
import com.hst.web.sys.entity.TUser;
import com.hst.web.sys.entity.TUserRole;

@Service
@Transactional
public class RegisterService {
	
	@Autowired
	IORDao dao;
	
	/**
	 * 注册用户
	 * @param reg
	 * @param emp
	 */
	public void register(Register reg,TCompanyEmployee emp,Model m) {
		Encoder encoder = Base64.getEncoder();
		String psw = new String(encoder.encode(reg.getPwd().getBytes()));
		
		TAccountIdentity ident = new TAccountIdentity();
		TAccountInfo accInfo = new TAccountInfo();
		TUser user = new TUser();
		TUserRole rel = new TUserRole();
		
		ident.setAddress(reg.getAddress());
		ident.setUserName(reg.getAccount());
		ident.setDynamicFace(reg.getDynamicFace());
		ident.setFullname(reg.getFullname());
		ident.setNationality(reg.getNationality());
		ident.setSex(reg.getSex());
		ident.setNativePlace(reg.getNativePlace());
		ident.setTelNumber(reg.getTelNumber());
		ident.setPapersNumber(reg.getPapersNumber());
		ident.setPapersType(reg.getPapersType());
		ident.setEmployeeCode(emp.getEmployeeCode());
		
		accInfo.setEmail(reg.getEmail());
		accInfo.setUserName(reg.getAccount());
		accInfo.setPassword(psw);
		accInfo.setTelNumber(reg.getTelNumber());
		
		user.setOperatorNbr(reg.getAccount());
		user.setPassword(psw);
		user.setEmployeeCode(emp.getEmployeeCode());
		user.setValidflag("1");
		user.setLoginName(reg.getFullname());
		
		dao.save(ident);
		dao.save(accInfo);
		user = dao.save(user);
		rel.setUserid(user.getId());
		rel.setRoleid("personal");
		dao.save(rel);
		
		m.addAttribute("success","success");
	}
	
	/**
	 *  保存个人信息
	 * @param ind
	 * @param info
	 * @param m
	 */
	public void save(TAccountIdentity ind,TAccountInfo info,Model m) {
		ind.setTelNumber(info.getTelNumber());
		dao.update(ind);
		dao.update(info);
		m.addAttribute("success","success");
	}
}
